#!/usr/bin/env python
import os
import cgi
import datetime
import logging

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.api import images
import database
from cookiemanager import LilCookies
import random
logging.getLogger().setLevel(logging.DEBUG)
def set_cookie():
	for i in range(5):
		return random.random()
	cookieutil = LilCookies(self, 'sadsadasdsadlakjdlasjdklsajdlkq32312312l3jlkejswqljsl1j2l321312sqws1232131swqs12321KLJKLJLJ231321eqwsasqe12')
	cookie_id = cookieutil.get_secure_cookie(name = 'cid')
	if result is None:
		cookie_id = cookieutil.set_secure_cookie(name = 'cid', value = str(random_number()), expires_days= 365*100)
	else:
		cookie_id = cookieutil.get_secure_cookie(name = 'cid')

class Creatives(webapp.RequestHandler):
    def get(self):
        query_str = "SELECT * FROM Creatives"
        creatives = database.db.GqlQuery (query_str)
        set_cookie()

	template_values = {
            'creatives': creatives,
            }
	path = os.path.join(os.path.dirname(__file__), 'templates/creatives.html')
        self.response.out.write(template.render(path, template_values))


class UploadCreatives(webapp.RequestHandler):
    def post(self):
        creative = database.Creatives()
        if users.get_current_user():
            creative.user = users.get_current_user()
        creative.name = self.request.get("name")
        creative.width = int(self.request.get("width"))
        creative.height = int(self.request.get("height"))
        creative.url = self.request.get("url")
        creative_img = self.request.get("img")
        creative.data = db.Blob(creative_img)
        creative.put()
        self.redirect('/')

class Image (webapp.RequestHandler):
    def get(self):
        set_cookie()
        creative = database.db.get(self.request.get("img_id"))
        ipaddress = self.request.remote_addr
        useragent = self.request.headers['User-Agent']
        cookieutil = LilCookies(self, 'sadsadasdsadlakjdlasjdklsajdlkq32312312l3jlkejswqljsl1j2l321312sqws1232131swqs12321KLJKLJLJ231321eqwsasqe12')
        cookie_value = cookieutil.get_secure_cookie(name = 'cid')
        if creative:
            self.response.headers['Content-Type'] = "image/png"
            self.response.out.write(creative.data)
            database.increment_impression(creative, ipaddress, useragent, cookie_value)
    
        else:
            self.response.out.write("No image")
class ClickTracker (webapp.RequestHandler):
	def post(self):
        cookieutil = LilCookies(self, 'sadsadasdsadlakjdlasjdklsajdlkq32312312l3jlkejswqljsl1j2l321312sqws1232131swqs12321KLJKLJLJ231321eqwsasqe12')
        cookie_value = cookieutil.get_secure_cookie(name = 'cid')
        ipaddress = self.request.remote_addr
        useragent = self.request.headers['User-Agent']
        creative = database.db.get(self.request.get("i"))
        click = self.request.get("click")
        database.increment_click(creative, ipaddress, useragent, cookie_value, click)
        self.redirect(click)



application = webapp.WSGIApplication([
    ('/Creatives', Creatives),
    ('/UploadCreatives', UploadCreatives),
    ('/adi/', ClickTracker)
    ('/img', Image)], debug=True)


def main():
    run_wsgi_app(application)


if __name__ == '__main__':
    main()
